<template>
  <a-modal
    :visible="visible"
    title="编辑施工内容"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :label-col="labelCol"
      :wrapperCol="wrapperCol"
      :rules="formRules"
      :model="formState"
    >
      <div v-for="item in columnsRule" :key="item.props">
        <a-form-item v-if="item.show" :label="item.label" :name="item.props">
          <!-- 文本框 -->
          <a-textarea
            v-if="item.ele === 'textarea'"
            v-model:value="formState[item.props]"
          ></a-textarea>
          <!-- 输入 -->
          <a-input
            v-if="item.ele === 'input'"
            v-model:value="formState[item.props]"
          ></a-input>
          <!-- 下拉 -->
          <a-select
            v-if="item.ele === 'select'"
            v-model:value="formState[item.props]"
            @change="onChange"
          >
            <a-select-option
              v-for="item in item.selectOpts"
              :key="item.value"
              :value="item.value"
              >{{ item.name }}</a-select-option
            >
          </a-select>
          <!-- 日期选择 -->
          <a-date-picker
            @change="onDataChange"
            style="width: 100%"
            v-if="item.ele === 'datePicker'"
            v-model:value="formState[item.props]"
          ></a-date-picker>
          <!-- 上传 -->
          <a-upload
            v-if="item.ele === 'upload'"
            :file-list="fileList"
            :remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              点击上传
            </a-button>
          </a-upload>
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch, defineProps, defineEmits } from "vue";
import {
  updateById,
  sgnrPictureUpload,
} from "@/api/module/constructionPreparation";
import { message } from "ant-design-vue";

const props = defineProps({
  visible: {
    type: Boolean,
  },
  record: {
    type: Object,
  },
});

const emits = defineEmits(["close"]);

// 表单实例
const formRef = ref();

// 表单设置
const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

// 表单渲染规则、
const columnsRule = ref([
  { ele: "textarea", props: "nr", label: "内容", show: true },
  { ele: "input", props: "dz", label: "地址", show: true },
  { ele: "input", props: "zrdw", label: "责任单位", show: true },
  {
    ele: "select",
    props: "zt",
    label: "状态",
    show: true,
    selectOpts: [
      { value: "0", name: "已完成" },
      { value: "1", name: "实施中" },
      { value: "2", name: "待实施" },
      { value: "3", name: "无此项" },
    ],
  },
  { ele: "input", props: "bz", label: "备注", show: true },
  { ele: "datePicker", props: "time", label: "完成时间", show: true },
  { ele: "datePicker", props: "time", label: "计划完成时间", show: false },
  { ele: "upload", props: "zp", label: "照片", show: true },
]);

// 表单数据
const formState = ref({
  nr: "",
  dz: "",
  zrdw: "",
  zt: "0",
  time: "",
  bz: "",
  zp: "",
});

// zp的自定义校验
const zpValidator = (rule, value) => {
  if (fileList.value.length === 0) {
    return Promise.reject("请上传");
  } else {
    return Promise.resolve();
  }
};

// 表单校验规则
const formRules = {
  nr: [{ required: true, message: "请输入", trigger: "blur" }],
  dz: [{ required: true, message: "请输入", trigger: "blur" }],
  zrdw: [{ required: true, message: "请输入", trigger: "blur" }],
  zt: [{ required: true, message: "请选择", trigger: "change" }],
  time: [{ required: true, message: "请选择", trigger: "change" }],
  bz: [{ required: true, message: "请输入", trigger: "blur" }],
  zp: [{ validator: zpValidator, trigger: "change" }],
};

// 照片文件
const fileList = ref([]);
const isUploadNum = ref(0);

// 上传的时候移除文件
const handleRemove = (file) => {
  console.log(file);
  if (!file.uid) {
    formState.value.zp = "";
  }
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 上传之前
const beforeUpload = (file) => {
  // 判断文件类型
  const imageType = ["image/jpeg", "image/png", "image/gif", "image/bmp"];
  const isType = imageType.includes(file.type);
  if (!isType) {
    return message.error("上传文件格式错误!");
  }
  fileList.value = [file];
  isUploadNum.value++;
  // 限制只能上传一个文件
  return false;
};

// 选择计划日期
const onDataChange = (data, dataString) => {
  formState.value.wcTime = dataString;
  formState.value.jhwcTime = dataString;
};

// 监听传递表单数据
watch(
  () => props.record,
  (newV, oldV) => {
    Object.assign(formState.value, newV);
    console.log(props.record);
    if (props.record.zp) {
      fileList.value.push({
        name: "测试图片.jpg",
        id: props.record.zp,
      });
    }
  }
);

// 监听状态
watch(
  () => formState.value.zt,
  (newV, oldV) => {
    if (newV === "0") {
      columnsRule.value[5].show = true;
      columnsRule.value[6].show = false;
      columnsRule.value[7].show = true;
    } else if (newV === "1") {
      columnsRule.value[5].show = false;
      columnsRule.value[6].show = true;
      columnsRule.value[7].show = true;
    } else if (newV === "2") {
      columnsRule.value[5].show = false;
      columnsRule.value[6].show = true;
      columnsRule.value[7].show = false;
    } else if (newV === "3") {
      columnsRule.value[5].show = false;
      columnsRule.value[6].show = false;
      columnsRule.value[7].show = false;
    }
  }
);

// 点击提交
const submit = async () => {
  await formRef.value.validate();
  // 数据状态判断
  if (formState.value.zt !== "3") {
    if (isUploadNum.value !== 0) {
      const formData = new FormData();
      fileList.value.forEach((item) => {
        formData.append("files", item);
      });
      const res = await sgnrPictureUpload(formData);
      formState.value.zp = res.data.zp[0];
    }
    // 无此项状态不需要添上传文件
  } else {
    formState.value.zp = "";
  }
  // 调用更新接口
  await updateById({
    zp: formState.value.zp,
    bz: formState.value.bz,
    id: formState.value.id,
    nr: formState.value.nr,
    time: formState.value.time,
    xmid: formState.value.xmid,
    zrdw: formState.value.zrdw,
    zt: formState.value.zt,
  });
  fileList.value = [];
  formRef.value.resetFields();
  emits("close", false);
};

// 点击取消
const cancel = (e) => {
  fileList.value = [];
  formRef.value.resetFields();
  emits("close", false);
};

// token
const tokenKey = localStorage.getItem("token_key");
const token = localStorage.getItem("token");
</script>
